from scrapy.core.downloader.contextfactory import ScrapyClientContextFactory
from OpenSSL import SSL

class CustomContextFactory(ScrapyClientContextFactory):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # 调用父类构造方法，传递所有参数
        self.verify_mode = SSL.VERIFY_NONE  # 禁用证书验证

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        # 从 crawler 的设置中加载实例
        return cls(*args, **kwargs)

    @classmethod
    def _from_settings(cls, settings, *args, **kwargs):
        # 从 settings 中加载实例（如果需要）
        return cls(*args, **kwargs)

    def getContext(self):
        # 获取 SSL 上下文并设置验证模式
        ctx = super().getContext()
        ctx.set_verify(self.verify_mode, lambda conn, cert, errno, depth, ok: True)
        return ctx